'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 帮助联盟成员
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var moment = require('moment');
var _ = require('lodash');
var constantUtil = require('../../../../util/constantUtil');
var Code = require('../../../../consts/code');
var unionGroupModel = require('../../../../models/unionGroupModel');
var unionGroupConf = require('../../../../config/unionGroupConf');
var unionHelpConf = require('../../../../config/unionHelpConf.js');
var PlayerManager = require('../../../../libs/playerManager');
var buildType = require('../../../../consts/buildType.js');
var taskService = require('../../../../services/taskService.js');
var unionHelpModel = require('../../../../models/unionHelpModel.js');
var haveHelpModel = require('../../../../models/haveHelpModel.js');
var unionGroupMgr = require('../../../../mgr/unionGroupMgr.js');
var haveHelpMgr = require('../../../../mgr/haveHelpMgr.js');

var is_new_version = false;

/**
 * 帮助联盟成员
 */
module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var help_role_id = msg.help_role_id;
    var share_id = msg.share_id;
    var help_type = msg.help_type;

    var union_group_model;
    var role_model;
    var help_role_model;
    var help_max_num = 0;
    var union_task_model;
    var union_id = 0;
    var all_help_list = [];
    var have_info = [];
    var item = null;
    var have_list_all = [];
    // jshint maxstatements:150
    var player_manager = new PlayerManager(role_id);
    var help_player_manager = new PlayerManager(help_role_id);
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['role', 'build', 'tech', 'unionTask', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'], cb);
            },
            function (cb) {
                role_model = player_manager.role;
                union_id = role_model.union_id;

                if (!union_id) {
                    return next(null, {
                        code: Code.UNION_IS_NOT_JOIN
                    });
                }
                unionGroupModel.getById(union_id, cb);
            },
            function (model, cb) {
                union_group_model = model;
                cb();
            },
            function (cb) {
                help_player_manager.getModel(['role', 'build', 'tech', 'unionTask', 'accrued'], cb);
            },

            function (cb) {
                help_role_model = help_player_manager.role;
                // 是否在同个公会
                if (!role_model.getUnionId() && !help_role_model.getUnionId() && role_model.getUnionId() !== help_role_model.getUnionId()) {
                    return next(null, {
                        code: Code.UNION_NOT_IDENTICAL
                    });
                }
                cb();
            },
            function (cb) {
                haveHelpModel.checkAlreadyHelp(role_id, help_role_id, help_type, share_id, cb);
            },
            function (already_help, cb) {
                if (already_help) {
                    return next(null, {
                        code: Code.UNION_IS_HELP_PEOPLE
                    });
                }

                unionHelpModel.findUnionHelpList(union_id, function (err, all_list) {
                    all_help_list = all_list;
                    cb();
                });
            },
            function (cb) {
                _.some(all_help_list, function (help_item) {
                    if (help_item.share_id == share_id && help_item.role_id == help_role_id && help_item.help_type == help_type) {
                        item = help_item;
                        return true;
                    }
                });
                if (!item) {
                    return next(null, {
                        code: Code.UNION_NOT_HELP
                    });
                }
                cb();
            },
            function (cb) {
                // 处理数据
                union_task_model = player_manager.unionTask;

                // 帮助加声望
                var union_help_reputation_reward = constantUtil.value('union_help_reputation_reward');
                union_task_model.helpAddReputation(union_help_reputation_reward);

                // help_type : 1--建筑     2--科技    3--联盟任务
                if ((+help_type) == 1) {
                    var help_build_model = help_player_manager.build;
                    var build_id = share_id;
                    var build_item = help_build_model.getBuildSchedule(build_id);
                    var build = help_build_model.getBuild(build_id);

                    // 建筑队列是否存在
                    if (!build_item) {
                        return next(null, {
                            code: Code.BUILD_NOT_SCHE
                        });
                    }

                    // 建筑队列是否存在
                    if (!build) {
                        return next(null, {
                            code: Code.BUILD_NOT_EXIST
                        });
                    }

                    // 加速
                    help_build_model.quick_schedule(share_id);

                    // 记录已帮助
                    have_info = [{
                        role_id: role_id,
                        union_id: union_id,
                        require_role_id: help_role_id,
                        share_id: share_id,
                        help_type: help_type,
                        only_id: item._id.toString()
                    }];
                    haveHelpModel.createHaveHelp(have_info, function (err) {});

                    // 增加声望
                    var now_reputation = union_task_model.max_reputation;
                    var max_reputation = constantUtil.value('union_help_reputation_limit');
                    if (now_reputation < max_reputation) {
                        union_task_model.addReputation(constantUtil.value('union_help_reputation_reward'));
                    }
                }

                // 科技帮助请求
                if ((+help_type) == 2) {
                    var tech_id = share_id;

                    var help_tech_model = help_player_manager.tech;

                    // 科技是否在队列中
                    if (help_tech_model.up_tech_id !== tech_id) {
                        return next(null, {
                            code: Code.TECH_QUE_EMPTY
                        });
                    }

                    // 加速
                    var total_time = help_tech_model.up_tech_end_tm - help_tech_model.up_tech_start_tm;
                    if (total_time > 0) {
                        var value = constantUtil.value('union_help_time_per');
                        var sub_time = parseInt(help_tech_model.up_tech_end_tm - total_time * (value / 100));
                        help_tech_model.setUpgradeTime(sub_time);
                    }

                    // 记录已帮助
                    have_info = [{
                        role_id: role_id,
                        union_id: union_id,
                        require_role_id: help_role_id,
                        share_id: share_id,
                        help_type: help_type,
                        only_id: item._id.toString()
                    }];

                    haveHelpModel.createHaveHelp(have_info, function (err) {});

                    // 增加声望
                    var tech_now_reputation = union_task_model.max_reputation;
                    var tech_max_reputation = constantUtil.value('union_help_reputation_limit');

                    if (tech_now_reputation < tech_max_reputation) {
                        union_task_model.addReputation(constantUtil.value('union_help_reputation_reward'));
                    }
                }

                // 联盟帮助---单个帮助次数统计
                taskService.addUnionHelpNum(player_manager);

                cb();
            },
            function (cb) {
                haveHelpModel.findUnionHelpList(role_id, function (err, all_have_list) {
                    have_list_all = all_have_list;
                    cb();
                });
            },
            function (cb) {
                if (!!have_list_all && item.help_max_num - 1 > 0) {
                    haveHelpMgr.sendHaveHelpChanged(
                        role_id, {
                            have_list: have_list_all,
                            is_modify: 1
                        },
                        function (err, fails) {
                            if (err) {
                                console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                                return;
                            }
                            cb();
                        }
                    );
                } else {
                    cb();
                }
            },
            function (cb) {
                if (!!item) {
                    // 刷新数据---帮助过后help_max_num - 1
                    var only_id_only_help = '' + item._id;
                    unionHelpModel.refreshHelpData(item, only_id_only_help, function (err) {
                        cb();
                    });
                } else {
                    cb();
                }

            },
            function (cb) {
                var max_num = item.help_max_num - 1;
                var item_modify = {
                    job: item.job,
                    share_id: item.share_id,
                    end_time: item.end_time,
                    help_type: item.help_type,
                    lv: item.lv,
                    help_max_num: max_num,
                    help_max_times: item.help_max_times,
                    name: item.name,
                    role_id: item.role_id,
                    union_id: item.union_id
                };

                if (max_num > 0) {
                    // 推送
                    var msg = {
                        is_modify: 3,
                        help_list: [item_modify]
                    };
                    unionGroupMgr.sendUnioHelpChangedMulti(
                        union_id,
                        msg,
                        function (err, fails) {
                            if (err) {
                                console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                                return;
                            }
                            cb();
                        }
                    );
                } else {
                    var have_modify_list = [];
                    have_modify_list.push({
                        require_role_id: item.role_id,
                        help_type: item.help_type,
                        share_id: item.share_id
                    });

                    // 推送已帮助列表
                    if (max_num === 0) {
                        haveHelpMgr.sendHaveHelpChanged(
                            role_id, {
                                have_list: have_modify_list,
                                is_modify: 2
                            },
                            function (err, fails) {
                                if (err) {
                                    console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                                    return;
                                }
                            }
                        );
                    }

                    var is_modify = 2;
                    if (is_new_version) {
                        is_modify = 3;
                    }

                    // 推送
                    var msg1 = {
                        is_modify: is_modify,
                        help_list: [item_modify]
                    };
                    unionGroupMgr.sendUnioHelpChangedMulti(
                        union_id,
                        msg1,
                        function (err, fails) {
                            if (err) {
                                console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                                return;
                            }
                        }
                    );

                    // 删除已帮助信息
                    haveHelpModel.removeMsg('' + item._id, function (err) {
                        cb();
                    });
                }
            },

            function (cb) {
                help_player_manager.save(cb);
            },

            function (cb) {
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            if (!!union_group_model) {
                union_group_model.save();
            }
            return next(null, {
                code: Code.OK,
            });
        }
    );
};
